const mysql = require('mysql2/promise');
const dbConfig = require("../config/db.config")

// 创建连接池
const pool = mysql.createPool({
  ...dbConfig,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});

// 测试数据库连接
async function testConnection() {
  try {
    const connection = await pool.getConnection();
    console.log('数据库连接成功');
    connection.release();
    return true;
  } catch (error) {
    console.log('数据库连接错误', error);
    return false;
  }
}

async function query(sql, params) {
  try {
    const [rows] = await pool.execute(sql, params);
    return rows;
  } catch (error) {
    console.error('查询错误:', error);
    throw error;
  }
}

async function getConnection() {
  return await pool.getConnection();
}

// 初始化时测试连接
(async () => {
  await testConnection();
})();

module.exports = {
  pool,
  query,
  getConnection,
  testConnection,
};
